<template>
  <div class="tab-container createSet active3">
    <!-- 第三步，添加活动商品-->
    <el-tabs type="border-card" v-model="activeTab">
      <el-tab-pane :label="noMutexProductLabel" name="noMutexTab">
        <div class="row-line-button t_r">
          <div style="width:100%">
            <kt-button class="searchButton" v-show="showButtons" size="mini" @click="searchGoodsFlag = !searchGoodsFlag" label="搜索" icon="el-icon-search"></kt-button>
            <!-- <kt-button size="mini" v-show="false" @click="allAdd()" class="searchButton" label="全部添加"></kt-button> -->
            <kt-button class="searchButton" v-show="showButtons" size="mini" @click="add" label="添加促销商品"></kt-button>
            <!-- <kt-button class="searchButton" v-show="showButtons" size="mini" @click="add" label="下载模板"></kt-button> -->
            <!-- <kt-button class="searchButton" v-show="showButtons" size="mini" @click="add" label="商品导入"></kt-button> -->
            <kt-button class="resetButton" v-show="showButtons" size="mini" @click="batchDelProduct" label="批量删除"></kt-button>
          </div>
        </div>
        <div v-if="searchGoodsFlag" class="m_b30" >
          <el-form :inline="true" :model="goodsListForm" size="mini" ref="goodsListForm" class="rightForm">
            <!-- <el-form-item  label="店铺：" prop="storeId">
              <template>
                <el-select v-model="goodsListForm.storeId" placeholder="全部" clearable>
                  <el-option
                    v-for="item in promotionStoreTableData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-form-item> -->
            <el-form-item label="商品名称：" prop="mpName">
              <el-input v-model="goodsListForm.mpName" clearable maxlength="80"   placeholder="商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品编码：" prop="mpCode">
              <el-input v-model="goodsListForm.mpCode" clearable maxlength="80"   placeholder="商品编码"></el-input>
            </el-form-item>
            <el-form-item label="商品分类：" prop="categoryName">
              <el-input v-model="goodsListForm.categoryName" clearable maxlength="80"   placeholder="商品分类"></el-input>
            </el-form-item>
            <el-form-item label="" prop="mpName">
              <el-button class="resetButton" plain size="mini" @click="resetForm('goodsListForm')">重置</el-button>
              <el-button class="resetButton"  size="mini" @click="goodsPageQuery" >查询</el-button>

            </el-form-item>
          </el-form>
        </div>
        <div class="tableTree">

            <el-table
              v-loading="noMuxProductLoading"
              :data="goodsList"
              @selection-change="repelSelectionChange"
              row-key="id"
              default-expand-all
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              class="tableStyle">
              <el-table-column align="left" width="30">
              <template slot="header" slot-scope="scope">
                <div class="isAllChecked" v-if="goodsList.length > 0">
                  <el-checkbox
                    :indeterminate="isIndeterminateProductCheck"
                    v-model="isAllProductChecked"
                    @change="handleCheckedAllProductChange"
                  ></el-checkbox>
                </div>
              </template>
            </el-table-column>
              <el-table-column width="40">
                <template slot-scope="scope">
                  <el-checkbox
                    :indeterminate="scope.row.isIndeterminateCheck"
                    v-model="scope.row.isCheck"
                    @change="handleCheckedProductChange(scope.row,$event)"
                  ></el-checkbox>
                </template>
              </el-table-column>
<!--              <el-table-column prop="mpCode" label="商品编码" align="left"  key="3" width="200"></el-table-column>-->
              <el-table-column prop="mpCode" label="商品ID" align="left"  key="3" width="200"></el-table-column>
              <el-table-column prop="mpName" label="商品名称" sortable width="200"></el-table-column>
              <el-table-column prop="categoryName" label="商品分类" align="center" key="5" width="200"></el-table-column>
              <el-table-column prop="stock" label="库存" align="center" width="200"></el-table-column>
              <el-table-column prop="storeName" label="所属商户" align="center" key="6" width="200"></el-table-column>
              <el-table-column prop="storeName" label="商户code" align="center" key="6" width="200"></el-table-column>
              <el-table-column prop="salePrice" label="零售价"  align="center" width="200">
              </el-table-column>
              <el-table-column prop="salePriceWithTax" label="一口价"  align="center"  v-if="this.frontPromType != 17" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.salePriceWithTax" @blur="updateProduct(scope.row)" :size="size"
                            placeholder="一口价" :disabled="scope.row.disabled" clearable oninput="value = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/g.test(value) ? value : ''" maxlength="10"/>
                </template>
              </el-table-column>
              <el-table-column prop="deptShare" label="平台分摊"  align="center"  v-if="costAllocationFlag == '1'" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.deptShare" @blur="updateProduct(scope.row)" :size="size"
                            placeholder="平台分摊" :disabled="scope.row.disabled" clearable oninput="value=value.replace(/[^\d]/g,'')" maxlength="10"/>
                </template>
              </el-table-column>
              <el-table-column prop="merchantShare" label="商户分摊" v-if="costAllocationFlag == '1'"  align="center" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.merchantShare" @blur="updateProduct(scope.row)" :size="size"
                            placeholder="商户分摊" :disabled="scope.row.disabled" clearable oninput="value=value.replace(/[^\d]/g,'')" maxlength="10"/>
                </template>
              </el-table-column>
              <el-table-column prop="stockLimit" label="活动库存"  align="center" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.stockLimit" @blur="updateProduct(scope.row)" :size="size"
                            placeholder="活动库存" :disabled="scope.row.disabled" clearable maxlength="10"/>
                </template>
              </el-table-column>
              <el-table-column prop="channelIndividualLimit" label="个人限购" align="center" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.channelIndividualLimit" @blur="updateProduct(scope.row)"
                            :size="size" placeholder="个人限购" :disabled="scope.row.disabled" clearable maxlength="10"/>
                </template>
              </el-table-column>
              <el-table-column prop="orderLimit" label="订单限购" align="center" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.orderLimit" @blur="updateProduct(scope.row)"
                            :size="size" placeholder="订单限购" :disabled="scope.row.disabled" clearable maxlength="10"/>
                </template>
              </el-table-column>

<!--              <el-table-column prop="salePrice" label="原价" align="center" key="7" width="200"></el-table-column>-->
              <!--<el-table-column prop="alreadyFrontCount" label="已预订数" align="center"  v-if="this.frontPromType != 20" width="200">
                <template slot-scope="scope">
                    {{scope.row.alreadyFrontCount}}
                </template>
              </el-table-column>-->


             <!--<el-table-column prop="frontMoney" label="订金" align="center"  v-if="this.frontPromType == 17" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.frontMoney" @blur="updateProduct(scope.row)" v-if="scope.row.typeOfProduct=='20'"
                            :size="size" placeholder="订金" :disabled="scope.row.disabled" clearable oninput="value = value.match(/^\d*(\.?\d{0,2})/g)[0]" maxlength="10"/>
                </template>
              </el-table-column>

              <el-table-column prop="frontMoneyDeductAmount" label="订金抵扣金额"  align="center" v-if="this.frontPromType == 17" width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.frontMoneyDeductAmount" @blur="updateProduct(scope.row)" v-if="scope.row.typeOfProduct=='20'"
                              :size="size" placeholder="订金抵扣金额" :disabled="scope.row.disabled" clearable oninput="value = value.match(/^\d*(\.?\d{0,2})/g)[0]" maxlength="10"/>
                  </template>
              </el-table-column>-->
                <!-- <el-table-column prop="channelMerchantLimit" label="商家限购" align="center" width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.channelMerchantLimit" @blur="updateProduct(scope.row)" :size="size" v-if="scope.row.typeOfProduct=='20'"
                              placeholder="商家限购" :disabled="scope.row.disabled"/>
                  </template>
                </el-table-column> -->


                <el-table-column label="操作" fixed="right" align="center" width="200">
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="delMerchantProducts(scope.row)"
                      type="text"
                      size="small">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
            </el-table>

            <!--分页栏-->
            <div class="toolbar t_r" >
              <el-pagination
                @size-change="goodsListHandleSizeChange"
                @current-change="goodsListHandleCurrentChange"
                :current-page="goodsListForm.start"
                :page-size="10"
                :page-sizes="[5,10, 20, 40]"
                layout="total, sizes, prev, pager, next, jumper"
                style="float:right;"
                :total="goodsListTotal">
              </el-pagination>
            </div>
<!--          </div>-->
        </div>
      </el-tab-pane>
      <el-tab-pane :label="mutexProductLabel" name="mutexTab">
        <div class="row-line-button t_r">
          <div style="width:100%">
            <!-- <el-button class="searchButton" @click="batchRenewAdd">批量重新添加</el-button> -->
          </div>
        </div>
        <div class="tableTree">

          <el-table :data="mutexProductList" v-loading="muxProductLoading"  row-key="id" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="batchRenewAddSelectionChange" style="width: 100%" class="tableStyle">
             <el-table-column align="left" width="30">
              <template slot="header" slot-scope="scope">
                <div class="isAllChecked" v-if="mutexProductList.length > 0">
                  <el-checkbox
                    :indeterminate="isIndeterminateCheck"
                    v-model="isAllChecked"
                    @change="handleCheckedAllChange"
                  ></el-checkbox>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="40">
              <template slot-scope="scope">
                <el-checkbox
                  :indeterminate="scope.row.isIndeterminateCheck"
                  v-model="scope.row.isCheck"
                  @change="handleCheckedChange(scope.row,$event)"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="mpCode" label="商品编码"   align="left" width="200"></el-table-column>
            <el-table-column prop="mpName" label="商品名称" width="200"></el-table-column>
            <el-table-column prop="categoryName" label="商品分类" width="200"></el-table-column>
            <el-table-column prop="stock" label="库存" width="200"></el-table-column>
            <el-table-column prop="salePrice" label="原价（元）" width="200"></el-table-column>
            <el-table-column prop="storeName" label="所属商户" width="200"></el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="390">
              <template slot-scope="scope">
                <el-button @click="getMutexInfo(scope.row)" v-if="scope.row.typeOfProduct==20" type="text" class="textButton" size="small">查看详情</el-button>
                <el-button @click="renewAdd(scope.row)" v-if="scope.row.typeOfProduct==10 || scope.row.typeOfProduct==20" type="text" class="textButton" size="small">重新添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="toolbar t_r" >
            <el-pagination
              @size-change="handleSizeChangeMutexProductList"
              @current-change="handleCurrentChangeMutexProductList"
              :current-page="mutexProductForm.start"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="mutexProductForm.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="mutexProductTotal"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>



    <!-- 互斥活动详情 -->
    <el-dialog :visible.sync="mutexPromotionVisible" title="互斥活动详情" width="70%">
      <div>
        <el-table :data="mutexPromotionList" ref="multipleTable" :row-class-name="tableRowClassName" :size="size">
          <el-table-column prop="promotionCode" width="280" label="互斥活动编码" sortable align="center"></el-table-column>
          <el-table-column prop="promName"  width="150" label="互斥活动名称" align="center">
              <template slot-scope="scope">
              <el-button @click="linkInfoByMutexProduct(scope.row.promotionId,scope.row.promType)" type="text" class="textButton" size="small">{{scope.row.promName}}</el-button>
              </template>
          </el-table-column>
          <el-table-column prop="goodsCategory"  width="350" label="互斥活动时间" align="center">
            <template slot-scope="scope">
                <span>{{scope.row.startTime}} - {{scope.row.endTime}}</span>
              </template>
          </el-table-column>
          <el-table-column prop="storeName" label="活动状态" align="center">
            <template slot-scope="scope">
              <span class="color333 font18" v-if="scope.row.status == 0">待提交</span>
              <span class="color333 font18" v-else-if="scope.row.status == 1">待提交</span>
              <span class="color333 font18" v-else-if="scope.row.status == 2">待审核</span>
              <span class="color333 font18" v-else-if="scope.row.status == 3">未开始</span>
              <span class="color333 font18" v-else-if="scope.row.status == 4">审核不通过</span>
              <span class="color333 font18" v-else-if="scope.row.status == 5">进行中</span>
              <span class="color333 font18" v-else-if="scope.row.status == 6">已过期</span>
              <span class="color333 font18" v-else-if="scope.row.status == 7">已关闭</span>
              <span class="color333 font18" v-else-if="scope.row.status == 8">已结束</span>
              <span class="color333 font18" v-else-if="scope.row.status == 9">活动草稿</span>
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="创建人" align="center"></el-table-column>
          <el-table-column prop="deptName"  label="创建组织" align="center"></el-table-column>
        </el-table>
        <!--分页栏-->
        <div class="toolbar t_r">
          <el-pagination
            @size-change="mutexPromotionListSizeChange"
            @current-change="mutexPromotionListCurrentChange"
            :current-page="mutexPromotionForm.start"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="mutexPromotionForm.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="mutexPromotionListTotal"
          ></el-pagination>
        </div>
      </div>
      <div slot="footer" class="dialog-footer t_c">
        <el-button class="searchButton" :size="size" @click.native="mutexPromotionVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加商品 -->
    <el-dialog :visible.sync="dialogVisibleTwo"  title="添加商品" :close-on-click-modal="false">
      <div slot="footer" class="dialog-footer" >
        <el-button :size="size" class="cancelButton" @click.native="dialogVisibleTwo = false">取消</el-button>
        <el-button :size="size" class="searchButton" @click="addBatch" :loading="productEditLoading">确定
        </el-button>
      </div>
      <el-tabs v-model="tabsIndex">
        <!-- <el-tab-pane label="商品管理" name="first"> -->
          <el-form :model="productForm"  ref="productForm" :size="size" :inline="true">
            <div class="col-sm-9">
              <el-form-item label="商品名称："  prop="chineseName" class="w178" label-width="112px">
                <el-input v-model="productForm.chineseName" auto-complete="off" clearable placeholder="商品名称"></el-input>
              </el-form-item>
              <el-form-item label="商品编码：" prop="code" class="w178">
                <el-input v-model="productForm.code" auto-complete="off" width="180" clearable placeholder="商品编码"></el-input>
              </el-form-item>
               <el-form-item label="商品分类：" prop="categoryName" class="w178" >
                <el-input v-model="productForm.categoryName" auto-complete="off" maxlength="80" clearable placeholder="商品分类"></el-input>
              </el-form-item>
            </div>
            <div class="col-sm-9" style="margin-top: 27px">
              <el-form-item label="所属商户名称：" prop="storeName" class="w178">
                <el-input v-model="productForm.storeName" auto-complete="off" maxlength="80" clearable placeholder="所属商户名称"></el-input>
              </el-form-item>
              <el-form-item label="商户Code：" prop="storeCode" class="w178">
                <el-input v-model="productForm.storeCode" auto-complete="off" maxlength="80" clearable placeholder="所属店铺名称"></el-input>
              </el-form-item>
            </div>
          </el-form>
          <el-row  class="mb30 mt20 t_r">
             <kt-button size="mini" @click="resetProductForm" class="resetButton" label="重置">重置</kt-button>
              <kt-button size="mini" @click="productFormFind(1)" class="searchButton"  icon="el-icon-search" label="搜索">搜索</kt-button>

            </el-row>

          <!--  商品列表 -->
          <div class="table-section">
            <el-table :data="tableDataTwo"
                      v-loading="productLoading"
                      @selection-change="addSelectionChangeProduct"
                      :header-cell-style="tableHeaderColor"
                      ref="multipleTable"
                      :size="size">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="thirdSpuId" label="商品编码" align="center"></el-table-column>
              <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
              <el-table-column prop="goodsCategory" label="商品分类" align="center"></el-table-column>
              <el-table-column prop="storeName" label="所属商户" align="center"></el-table-column>
              <el-table-column prop="storeCode" label="商户Code" align="center"></el-table-column>
              <el-table-column prop="salePriceScope" label="原价（元）" align="center"></el-table-column>
            </el-table>
            <div class="toolbar t_r" v-if="tableDataTwo.length > 0">
              <el-pagination
                @size-change="producthandleSizeChange"
                @current-change="producthandleCurrentChange"
                :current-page="productForm.start"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="productForm.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="productListTotal"
              ></el-pagination>
            </div>
          </div>
        <!-- </el-tab-pane> -->
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import marketRequest from "@/market/request/marketRequest";
import { getAllRow, changeChild, changeParent } from "@/assets/js/tableTree.js";

export default {
  components: {
    KtButton,
    marketRequest
  },
  data() {
    return {
      size: "small",
      // goodsSpuIdListSelection:[],  //批量删除时候临时存储的spuIds
      // goodsSkuIdListSelection:[],  //批量删除时候临时存储的skuIds
      repelSelection: [],

      pomotionListObject: { productPromotionList: [] },
      productAddSelection: [],
      tableDataTwo: [],

      goodsList: [],
      goodsListForm: {
        start: 1,
        limit: 10,
        promotionId: null,
        goodsName: null,
        categoryName: null,
        storeIds: [],
        merchantId: null,
        mpCode: null,
        mpName: null
      },

      frontPromType: null,
      goodsListTotal: 0,
      alreadyGoodsTotal: "",

      goodsSearchForm: {
        promotionId: null,
        merchantName: null
      },

      dialogVisibleTwo: false,
      tabsIndex: "first",
      productForm: {
        start: 1,
        limit: 10,
        goodsName: null,
        goodsCategory: null,
        thirdSpuId: null,
        spuId: null,
        promotionId: null,
        storeName: null,
        chineseName: null,
        code: null
      },
      promotionId: 0,
      productTableData: [],
      productEditLoading: false,
      searchGoodsFlag: false,

      noMutexProductLabel:"生效商品（0）",
      mutexProductForm:{
        promotionId: null,
        mutexFlag:1,//互斥标识
        start: 1,
        limit: 10
      },
      mutexProductList:[],
      mutexProductTotal:0,
      mutexProductLabel:"互斥商品（0）",
      showButtons:true,
      mutexPromotionForm:{
        promotionId: null,
        promType:9,
        start:1,
        limit:10,
      },
      promotionStoreTableData: [],
      mutexPromotionList:[],
      mutexPromotionListTotal:0,
      mutexPromotionVisible:false,
      batchRenewAddSelection:[],
      // unMutexFlag: true,
      activeTab: "noMutexTab",
      noMuxProductLoading: false,
      muxProductLoading: false,
      productLoading: false,

      isAllChecked: false,//全选
      isIndeterminateCheck: false,//全选 checkbox 的不确定状态
      allData: [],//全选 操作数据

      isAllProductChecked: false,//全选
      isIndeterminateProductCheck: false,//全选 checkbox 的不确定状态
      allProductData: [],//全选 操作数据

      storeIdList: [],
      productListTotal: 0,
      costAllocationFlag:null,
    };
  },
  methods: {

    init(promotionId, frontPromType , storeIdList,costAllocationFlag) {
      this.promotionId = promotionId;
      this.frontPromType = frontPromType;
      this.goodsListForm.promotionId = promotionId;
      this.productForm.promotionId = promotionId;
      this.goodsSearchForm.promotionId = promotionId;
      this.mutexPromotionForm.promotionId = promotionId;
      this.mutexProductForm.promotionId = promotionId;
      this.productForm.storeIds = [];
      this.storeIdList = storeIdList;
      this.costAllocationFlag = costAllocationFlag;
      this.goodsListHandleCurrentChange(1);
      this.getMutexProductList();
      // this.getPromotionStoreTableData();
    },
    producthandleSizeChange(pageSize) {
      this.productForm.start = 1;
      this.productForm.limit = pageSize;
      this.productFormFind();
    },
    producthandleCurrentChange(pageNum) {
      this.productForm.start = pageNum;
      this.productFormFind();
    },
    add() {
      this.dialogVisibleTwo = true;
      // this.goodsSpuIdListSelection = null;
      this.productAddSelection = []; // 清空之前数据
      this.productFormFind();
    },
    repelSelectionChange(val) {
      this.repelSelection = val;
    },
    // 批量添加商品
    addBatch() {
      let this_ = this;

      for (var i = 0; i < this.productAddSelection.length; i++) {
        let param = {
          promotionId: this.goodsListForm.promotionId,
          spuId: this.productAddSelection[i].id,
          storeIds: []
        };

        marketRequest.promotionMerchantProductAddAll(param, function(resp) {
          if (resp.code == "0000") {
            this_.dialogVisibleTwo = false;
            this_.goodsPageQuery();
            this_.getMutexProductList();
          }
        });
      }
    },
    handleCheckedAllChange(value) {
      ////
      this.isIndeterminateCheck = false;

      this.allData.forEach(f => {
        f.isCheck = value;
        f.isIndeterminateCheck = false;
      });
    },
    goodsListHandleCurrentChange(val) {
      this.goodsListForm.start = val;
      this.goodsPageQuery();
    },
    goodsListHandleSizeChange(val) {
      this.goodsListForm.limit = val;
      this.goodsPageQuery();
    },
    // 查询商品列表
    goodsPageQuery(tab) {
      //
      // if(tab == undefined){
      //   this.unMutexFlag = true;
      // }else if(tab != undefined && tab != null && tab.name == "noMutexTab"){
      //   this.unMutexFlag = true;
      // }else {
      //   this.unMutexFlag = false;
      // }
      let this_ = this;
      this_.noMuxProductLoading = true;
      let callback = function(res) {
        if (res.code == "0000") {
          this_.noMuxProductLoading = false;
          this_.goodsList = res.data.rows;
          this_.goodsListTotal = res.data.total;
          if(res.data.totalCount>9999){
            this_.noMutexProductLabel = "生效商品（9999+）";
          }else{
            this_.noMutexProductLabel = "生效商品（"+res.data.totalCount+"）";
          }
          this_.allProductData = getAllRow(this_.goodsList, [],this_.costAllocationFlag);
          // this_.isAllProductChecked= false;
          //   this_.isIndeterminateProductCheck= false;
        } else {
            this_.noMutexProductLabel = "生效商品（0）";
        }
      };
      marketRequest.getProductListV3(this.goodsListForm, callback);
      // if(tab.index==0){
      //   this.showButtons = true;
      // }else{
      //   this.showButtons = false;
      // }
    },
    checkProductLimits(row){
      var reg = /^(?!0(\.0{1,2})?$)(\d(\.\d{1,2})?|10)$/;//0-10
      var priceReg = /^\d+\.?\d{0,2}$/; // 2位小数
      var regPos = /^[1-9]([0-9]*)$/; // 非负整数

        // row.frontMoney //定金
        // row.frontMoneyDeductAmount //定金抵扣金额

      // if(!row.frontMoney){
      //   this.$message({ message: "请输入商品订金金额", type: "error" });
      //   return false;
      // }
      // if(!priceReg.test(row.frontMoney)){
      //   this.$message({ message: "订金为正数，支持输入2位小数", type: "error" });
      //   return false;
      // }
      if(this.frontPromType == 17){
        if(!row.salePriceWithTax){
          this.$message({ message: "请输入预售价", type: "error" });
          return false;
        }
        if(!row.frontMoney){
          this.$message({ message: "请输入商品订金金额", type: "error" });
          return false;
        }
        if(!priceReg.test(row.frontMoney)){
          this.$message({ message: "订金为正数，支持输入2位小数", type: "error" });
          return false;
        }
        if(!row.frontMoneyDeductAmount){
          this.$message({ message: "请输入商品订金抵扣金额", type: "error" });
          return false;
        }
        if(!priceReg.test(row.frontMoneyDeductAmount)){
          this.$message({ message: "订金抵扣金额为正数，支持输入2位小数", type: "error" });
        return false;
        }
        if(Number(row.frontMoneyDeductAmount) < Number(row.frontMoney)){
          this.$message({ message: "订金抵扣金额不能小于订金金额", type: "error" });
          return false;
        }
      }else{
        if(!row.salePriceWithTax){
          this.$message({ message: "请输入一口价", type: "error" });
          return false;
      }
      }
      // if(!row.channelStoreLimit){
      //   this.$message({ message: "请输入店铺限购", type: "error" });
      //   return false;
      // }
      // if(!row.channelIndividualLimit){
      //   this.$message({ message: "请输入个人限购", type: "error" });
      //   return false;
      // }

      if(!regPos.test(row.orderLimit)&&row.orderLimit){
        this.$message({ message: "订单只能输入正整数", type: "error" });
        return false;
      }
      if (row.deptShare || row.merchantShare) {
        if (!regPos.test(row.deptShare) && row.deptShare) {
          this.$message({message: "平台分摊只能输入正整数", type: "error"});
          return false;
        }
        if (!regPos.test(row.merchantShare) && row.merchantShare) {
          this.$message({message: "商户分摊只能输入正整数", type: "error"});
          return false;
        }
        if (Number(row.deptShare) + Number(row.merchantShare) != 100) {
          this.$message({message: "平台和商家分摊比例总和不为100", type: "error"});
          return false;
        }
      }
      if(!regPos.test(row.stockLimit)&&row.stockLimit){
        this.$message({ message: "活动库存只能输入正整数", type: "error" });
        return false;
      }
      if(!regPos.test(row.channelIndividualLimit)&&row.channelIndividualLimit){
        this.$message({ message: "个人限购只能输入正整数", type: "error" });
        return false;
      }
      if(Number(row.stockLimit) > row.stock && row.stockLimit ){
        this.$message({ message: "活动库存需小于等于商品库存", type: "error" });
        return false;
      }
      return true;
    },
    // 更新商品信息
    updateProduct(val) {
      let callback = function(res) {
        if (res.code == "0000") {
        } else {
          //alert("修改失败");
        }
      };
      if(parseFloat(val.stockLimit)>parseFloat(val.stock)){
        this.$message({ message: "活动库存不可大于商品库存", type: "error" });
        return false;
      }
      let temp = {};
      temp.id = val.id;
      temp.salePriceWithTax = val.salePriceWithTax;
      temp.frontMoney = val.frontMoney;
      temp.frontMoneyDeductAmount = val.frontMoneyDeductAmount;
      temp.channelMerchantLimit = val.channelMerchantLimit;
      temp.channelStoreLimit = val.channelStoreLimit;
      temp.channelIndividualLimit = val.channelIndividualLimit;
      temp.orderLimit = val.orderLimit;
      temp.deptShare = val.deptShare;
      temp.merchantShare = val.merchantShare;
      temp.stockLimit = val.stockLimit;
      var flag = this.checkProductLimits(temp);
      if(!flag){
        return false;
      }
      this.utils.request.presellProductUpdate(temp, callback);
    },

    // 删除促销商品
    delMerchantProducts(row) {
      // this.$confirm("是否确认删除？", "提示", {
      //   type: "warning",
      //   closeOnClickModal: false,
      // })
      //   .then(() => {
          let this_ = this;
          let callback = function(res) {
            if (res.code == "0000") {
              // 成功查询本地促销商品
              this_.goodsListHandleCurrentChange(1);
            } else {
              this.$message({ message: "删除商品失败", type: "fail" });
            }
          };
          let param = {};
          param.id = row.id;
          param.typeOfProduct = row.typeOfProduct;
          marketRequest.promotionMerchantProductDelete(param, callback);
        // })
        // .catch(() => {});
    },

    // 批量删除
    batchDelProduct() {
      let ids = [];
      this.allProductData.forEach(function(item,index,array){
        //判断父下面是否全选
        if(item.typeOfProduct == '10' && item.isCheck){
          if(item.children && item.children.length > 0){
            let isCheckItems = item.children.filter(function (subItem, index) {
              return !subItem.isCheck;
            });
            if(!(isCheckItems && isCheckItems.length > 0)){
              ids.push(item.id);
            }
          }else{
            ids.push(item.id);
          }
        }else if(item.typeOfProduct == '20' && item.isCheck){
          ids.push(item.id);
        }
      });
      if (ids.length == 0) {
        this.$message({ message: "未选择删除条目", type: "error" });
        return;
      }

      this.$confirm('确认批量删除已选内容？', "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            // 成功查询本地促销商品
            // this_.getProductListV2(0, null);
            this_.goodsListHandleCurrentChange(1);
          } else {
            this.$message({ message: "删除商品失败", type: "fail" });
          }
        };
        let param = {};
        param.ids = ids;
        marketRequest.promotionMerchantProductDeleteBatch(param, callback);
      }).catch(() => {});
    },
    // // 批量删除
    // batchDel() {
    //   if (this.repelSelection.length == 0) {
    //     this.$message({ message: "未选择删除条目", type: "error" });
    //     return;
    //   }
    //   this.$confirm("确认批量删除已选内容？", "提示", {
    //     type: "warning",
    //     closeOnClickModal: false,
    //   })
    //     .then(() => {
    //       let this_ = this;
    //       let callback = function(res) {
    //         if (res.code == "0000") {
    //           // 成功查询本地促销商品
    //           this_.goodsListHandleCurrentChange(1);
    //         } else {
    //           this.$message({ message: "删除商品失败", type: "fail" });
    //         }
    //       };
    //       let ids = this.repelSelection.map(item => item.id).toString();
    //       let idArray = (ids + "").split(",");
    //       let param = {};
    //       param.ids = idArray;
    //       marketRequest.promotionMerchantProductDeleteBatch(param, callback);
    //     })
    //     .catch(() => {});
    // },

    addSelectionChangeProduct(val) {
      let this_ = this;
      this_.productAddSelection = val;
    },
    //修改table header的背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color:rgb(250,250,250);";
      }
    },

    resetProductForm() {
      this.resetForm("productForm");
      this.productForm.promotionId = this.promotionId;
      this.productFormFind();
    },

    productFormFind(start, limit) {
      if (start) {
        this.productForm.start = start;
      }
      if (limit) {
        this.productForm.limit = limit;
      }
      let that_ = this;
      that_.productLoading = true;
      this.productForm.storeIds = this.storeIdList;
      that_.utils.request.queryPageProductManagementNew(
        this.productForm,
        function(resp) {
          if (resp.code == "0000") {
            that_.productLoading = false;
            // that_.tableDataTwo = resp.data.rows;
            that_.tableDataTwo = resp.data.rows.map((ele, index) => {
                let spu = {};
                spu.id = ele.id;
                spu.thirdSpuId = ele.code;
                spu.goodsName = ele.chineseName;
                // spu.totalStock = ele.totalStock;
                spu.goodsCategory = ele.fullNamePath;
                spu.merchantName = ele.merchantName;
                spu.storeName = ele.storeName;
                spu.salePriceScope = ele.salePriceWithTax;
                // spu.measureUnit = ele.measureUnit;
                return spu;
              });
              that_.productListTotal = Number(resp.data.total);
          }
        }
      );
    },
    //table的双色条纹
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },

    allAdd() {
      let this_ = this;
      let param = {
        promotionId: this.goodsListForm.promotionId,
        storeIds: []
      };

      marketRequest.promotionMerchantProductAddAll(param, function(resp) {
        if (resp.code == "0000") {
          this_.dialogVisibleTwo = false;
          this_.goodsPageQuery();
          this_.getMutexProductList();
        }
      });
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.goodsPageQuery();
      }
    },

    resetFormProduct(formName){
      this.resetForm(formName);
    },

    /**
     * 查询互斥商品
     */
    getMutexProductList() {
      var this_ = this;
      this_.muxProductLoading = true;
      marketRequest.getProductListV3(this.mutexProductForm, res => {
        if (res.code == "0000") {
          this_.muxProductLoading = false;
          this_.mutexProductList = res.data.rows;
          this_.mutexProductTotal = res.data.total;
          //操作数据
          this_.allData = getAllRow(this_.mutexProductList, []);
          this_.isAllChecked = false;
          this_.isIndeterminateCheck = false;
          if(this_.mutexProductTotal>9999){
            this_.mutexProductLabel = "互斥商品（9999+）";
          }else{
            this_.mutexProductLabel = "互斥商品（"+res.data.totalCount+"）";
          }
        }
      });
    },
    /**
     * 每页条数改变触发
     */
    handleSizeChangeMutexProductList(val){
      this.mutexProductForm.limit = val;
      this.mutexProductForm.start = 1;
      this.getMutexProductList();
    },
    /**
     * 换页刷新
     */
    handleCurrentChangeMutexProductList(val){
      this.merchantProductSearchForm.start = val;
      this.getMutexProductList();
    },
    handleCheckedAllProductChange(value) {
      ////
      this.isIndeterminateProductCheck = false;

      this.allProductData.forEach(f => {
        f.isCheck = value;
        f.isIndeterminateCheck = false;
      });
    },
    /**
     * 互斥商品重新添加
     */
    renewAdd(row){
      let that = this;
      let param = {};
      var productIdList = [];
      param.promotionId = row.promotionId;
      param.promotionType = 1;
      if(row.typeOfProduct == '10'){
          row.children.forEach(item=>{
            productIdList.push(item.id);
          })
      }else if(row.typeOfProduct == '20'){
        productIdList.push(row.id);
      }
      param.productIdList = productIdList;
      this.utils.request.renewAddMutexProduct(param,res=>{
        if(res.code=='0000'){
          that.getMutexProductList();
          that.goodsPageQuery();
          let data = res.data;
          if(data.businessCode == '0001'){
            that.$message({message: data.businessMsg, type: "success"});
          }else if(data.businessCode == '0002'){
            that.$message({message:data.businessMsg, type: "error"})
          }else if(data.businessCode == '0003'){
            that.$alert(data.businessMsg, '提示', {
              confirmButtonText: '知道了',
              callback: action => {}
            });
          }
        }
      });
    },

    /**
     * 批量重新添加选择数据
     */
    batchRenewAddSelectionChange(val) {
      this.batchRenewAddSelection = val;
    },

    /**
     * 批量重新添加
     */
    batchRenewAdd(){
      let that = this;
      let param = {};
      var productIdList = [];
      param.promotionId = this.promotionId;
      param.promotionType = 1;
      this.allData.forEach(function(item,index,array){
        if(item.typeOfProduct == '20' && item.isCheck){
          productIdList.push(item.id);
        }
      });
      if (productIdList.length < 1) {
        this.$message({ message: "未选择重新添加条目", type: "error" });
        return;
      }
      param.productIdList = productIdList;
      this.utils.request.renewAddMutexProduct(param,res=>{
        if(res.code=='0000'){
          that.getMutexProductList();
          that.goodsPageQuery();
          let data = res.data;
          if(data.businessCode == '0001'){
            this.$message({message: data.businessMsg, type: "success"});
          }else if(data.businessCode == '0002'){
            this.$message({message:data.businessMsg, type: "error"})
          }else if(data.businessCode == '0003'){
            this.$alert(data.businessMsg, '提示', {
              confirmButtonText: '知道了',
              callback: action => {}
            });
          }
        }
      });
    },
    getPromotionStoreTableData(){
      let this_ = this;
      let param = {"promotionId":this.promotionId,"merchantType":2,"pageNo":1, "pageSize":100000};
      this.utils.request.promotionMerchantList(param, res => {
        if (res.code == "0000") {
          this_.promotionStoreTableData = res.data.list.map((ele, index) => {
            let promotionStore = {};
            promotionStore.id = ele.storeId;
            promotionStore.name = ele.storename;
            return promotionStore;
          });
        }
      });
    },
    /**
     * 生效商品 互斥商品tab选中触发
     */
    productTabs(tab){
      if(tab.index==0){
        this.showButtons = true;
      }else{
        this.showButtons = false;
      }
    },
    handleCheckedChange(row, checked) {
      ////
      if (row.isIndeterminateCheck) {
        row.isCheck = true;
        checked = true;
      }
      row.isIndeterminateCheck = false;

      changeChild(row, checked);
      changeParent(row, this.allData);

      this.isAllChecked = this.allData.every(e => {
        return e.isCheck;
      });

      this.isIndeterminateCheck =
        !this.isAllChecked &&
        this.allData.some(e => {
          return e.isCheck;
        });
    },
    handleCheckedProductChange(row, checked) {
      ////
      if (row.isIndeterminateCheck) {
        row.isCheck = true;
        checked = true;
      }
      row.isIndeterminateCheck = false;

      changeChild(row, checked);
      changeParent(row, this.allProductData);

      this.isAllProductChecked = this.allProductData.every(e => {
        return e.isCheck;
      });

      this.isIndeterminateProductCheck =
        !this.isAllProductChecked &&
        this.allProductData.some(e => {
          return e.isCheck;
        });
    },
    /**
     * 互斥商品查看详情
     */
    getMutexInfo(row){
      let that = this;
      this.mutexPromotionForm.promotionMerchantProductId = row.id;
      this.getPromotionMutexListByProductId();
    },
    getPromotionMutexListByProductId(){
      let that = this;
      this.utils.request.getPromotionMutexListByProductId(this.mutexPromotionForm,res=>{
        if(res.code=='0000'){
            that.mutexPromotionList = res.data.rows;
            that.mutexPromotionListTotal = res.data.total;
            that.mutexPromotionVisible = true;
        }
      });
    },

    /**
     * 每页条数改变触发
     */
    mutexPromotionListSizeChange(val){

      this.mutexPromotionForm.limit = val;
      this.mutexPromotionForm.start = 1;
      this.getPromotionMutexListByProductId();
    },
    /**
     * 换页刷新
     */
    mutexPromotionListCurrentChange(val){

      this.mutexPromotionForm.start = val;
      this.getPromotionMutexListByProductId();
    },
    /**
     * 点击活动名称跳转详情
     */
    linkInfoByMutexProduct(promotionId,type){
      if(type == 1){
        this.$router.push({ path: "/SinglePromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/SinglePromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 2){
        this.$router.push(`/FullNumPromotionDetailNew?id=${promotionId}&auth=0`);
      }else if(type == 3){
        this.$router.push({ path: "/FullPromotionDetailNew/" + promotionId + "/0"});
        //this.$router.push(`/FullPromotionDetailNew?id=${promotionId}&auth=0`);
      }else if(type == 4){
        this.$router.push(`/SeckillDetail?promotionId=${promotionId}`);
      }else if(type == 5){
        this.$router.push({ path: "/GiftPromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/GiftPromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 6){
        this.$router.push({ path: "/ComplexPromotionInfo/" + promotionId});
      }else if(type == 7){
        this.$router.push({ path: "/XofferPromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/XofferPromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 8){
        this.$router.push({ path: "/IncreasePromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/IncreasePromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 9){
        this.$router.push(`/QueryPresellPromotion?value=${promotionId}&auth=0`);
      }else if(type == 10){
        this.$router.push("/GroupDetailPromotion?id=" + `${promotionId}`);
      }else if(type == 12){
        this.$router.push(`/QueryPromotion?value=${promotionId}&auth=0`);
      }
    }
  },
  mounted() {}
};
</script>
<style lang="scss" scoped>
</style>
